import datamodel
import utils

import logging
from datetime import datetime

from google.appengine.ext import db

class Area():
	def create(self, dispatcher):
		logging.info("create")
		parenttrip = self.getParentTrip(dispatcher.modelObject.tripKey, dispatcher)

		area = datamodel.Area(parent=parenttrip)
		area.name = dispatcher.modelObject.name
		area.city = dispatcher.modelObject.city
		area.userId = dispatcher.userId

		area.tripKey=str(parenttrip.key())
		area.put()
		parenttrip.areas.append(area.key())
		parenttrip.put()
		return area

	def update(self, dispatcher):
		logging.info("update %s", dispatcher.modelObject.name)
		dispatcher.modelObject.put()
		return dispatcher.modelObject
   
	def delete(self, dispatcher):
		logging.info("delete")
		tripKey = dispatcher.modelObject.tripKey
		parenttrip = self.getParentTrip(tripKey, dispatcher)
		self.deleteArea(dispatcher.modelObject,parenttrip)


	def get(self, dispatcher):
		logging.info("get")
		if dispatcher.request.get('key'):
			logging.info("getting area by key")
			return dispatcher.modelObject
		else:
			logging.info("getting all areas for user")
			query = datamodel.Area.all()
			query.order('name')
			if not dispatcher.isAdminData:
				query.filter('userId =', dispatcher.userId)
			return query.fetch(100)

	def decode(self, decodeType, inputStr, inputObj, dispatcher):
		if inputObj == None:
			inputObj = datamodel.Area()
		return utils.GqlDecoder().decode(inputStr, inputObj)

	def encode(self, decodeType, outputObj, dispatcher):
		return utils.GqlEncoder().encode(outputObj)

	def deleteArea(self,area,parenttrip):
		db.delete(area.hotels)
		parenttrip.areas.remove(area.key())
		area.delete();
		parenttrip.put()
	
	def getParentTrip(self,key,dispatcher):
		parenttrip = datamodel.Trip().get(key)
		if not dispatcher.isAdminData:
			if (parenttrip.userId != dispatcher.userId):
				raise Exception("No Permissions")
		return parenttrip;
